package com.syg.servlet04;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * 禁用Cookie后,共享Session中的数据
 */
@WebServlet("/disableCookie")
public class _03_Disable_Cookie extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置输出响应编码
        resp.setContentType("text/html;charset=UTF-8");
        //获取响应输出流
        PrintWriter respOut = resp.getWriter();
        //创建session(获取session)
        HttpSession session = req.getSession();
        respOut.write("本网站有如下书：<br/>");
        respOut.write("req.getContextPath()得到的是项目名:/JavaServlet==>"+req.getContextPath());
        respOut.write("<br/>");
        Set<Map.Entry<String,Book>> set = DB.getAll().entrySet();
        for(Map.Entry<String,Book> me : set){
            Book book = me.getValue();
            String url =req.getContextPath()+ "/buyServlet?id=" + book.getId();
            //response. encodeURL(java.lang.String url)用于对表单action和超链接的url地址进行重写
            url = resp.encodeURL(url);//将超链接的url地址进行重写
            respOut.println(book.getName()  + "   <a href='"+url+"'>购买</a><br/>");
        }
    }

    /**
     * @author syg
     * 模拟数据库
     */
    static class DB{
        private static Map<String,Book> map = new LinkedHashMap<String,Book>();
        static{
            map.put("1", new Book("1","javaweb开发"));
            map.put("2", new Book("2","spring开发"));
            map.put("3", new Book("3","hibernate开发"));
            map.put("4", new Book("4","struts开发"));
            map.put("5", new Book("5","ajax开发"));
        }

        public static Map<String,Book> getAll(){
            return map;
        }
    }

    /**
     * 创建书的实体类
     */
    static class Book{

        private String id;
        private String name;

        public Book() {
            super();
        }
        public Book(String id, String name) {
            super();
            this.id = id;
            this.name = name;
        }
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
}
